<template>
  <basic-modal
    title="交易流水"
    v-bind="$attrs"
    show-confirm
    :show-footer="false"
    width="900px"
  >
    <n-grid :col="24" y-gap="10">
      <n-grid-item span="24">
        <n-card
          size="small"
          :title="`问题检查清单`"
          content-class="flex flex-col flex-1"
        >
          <n-spin :show="snDetailLoading">
            <div class="flex-1">
              <n-scrollbar content-class="max-h-36">
                <n-space vertical v-if="snCheckResult.length">
                  <div
                    class="question-item"
                    v-for="checkResult in snCheckResult"
                    :key="checkResult.id"
                    :class="{
                      'question-item--active': checkResult.result === '1',
                    }"
                    @click.stop="handleChangeCheckResult(checkResult)"
                  >
                    <span class="font-bold leading-[28px]">
                      {{ checkResult.questionName }}
                    </span>
                    <n-icon
                      v-show="checkResult.result === '1'"
                      size="24"
                      :color="CommonConfig.primaryColor"
                    >
                      <CheckmarkCircleSharp />
                    </n-icon>
                  </div>
                </n-space>
                <n-empty description="暂无数据" v-else> </n-empty>
              </n-scrollbar>
            </div>
            <div class="flex justify-end mt-2">
              <n-popconfirm @positive-click="handleResetSnCheckResult">
                <template #trigger>
                  <n-button :loading="updateSnResultFlag" class="mr-1">
                    重置
                  </n-button>
                </template>
                确定要重置吗？
              </n-popconfirm>

              <n-popconfirm @positive-click="handleUpdateSnCheckResult">
                <template #trigger>
                  <n-button :loading="updateSnResultFlag" type="primary">
                    保存
                  </n-button>
                </template>
                确定要修改吗？
              </n-popconfirm>
            </div>
          </n-spin>
        </n-card>
      </n-grid-item>
      <n-grid-item span="24">
        <n-card size="small" content-class="flex flex-col flex-1">
          <div class="pb-2">
            <n-grid :col="24" x-gap="10">
              <n-gi :span="12">
                <n-date-picker
                  type="daterange"
                  clearable
                  v-model:value="paginationResult.createTimeRange"
                  @update:value="handleSearch"
                />
              </n-gi>
              <n-gi :span="12">
                <n-select
                  clearable
                  :options="snTransactionTypesList"
                  placeholder="请选择业务类型"
                  v-model:value="paginationResult.type"
                  @update:value="handleSearch"
                />
              </n-gi>
            </n-grid>
          </div>
          <BasicTable
            :table-props="tableResult"
            :columns="columns"
            :pagination-props="paginationResult"
            maxHeight="66vh"
          />
        </n-card>
      </n-grid-item>
    </n-grid>
  </basic-modal>
</template>
<script lang="ts" setup>
import { ref, useAttrs, watch, h } from "vue";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
import { cloneDeep, get, debounce } from "lodash-es";
import { NButton, NIcon, NTag } from "naive-ui";
import { CheckmarkCircleSharp, Eye } from "@vicons/ionicons5";
import CommonConfig from "@/config/uiTheme/common";
import {
  getSnCheckResult,
  updateSnCheckResult,
} from "@/api/inventory/inventory.api";
import {
  snTransactionTypes,
  snTransactionTypesList,
} from "@/enums/orders/index";
import { snStatus } from "@/enums/sn/snStatusEnum";
import { getSnTransactionLogs } from "@/api/transactionLogs/transactionLogs.api";
import { useTableHook } from "@/components/normal/basicTable/useTableHook";
import * as RouterNames from "@/router/routerNames";
import { ISnTransactionProps } from "./props";

const columns = [
  {
    title: "#",
    type: "index",
    key: "key",
    width: "5%",
    render: (_: any, index: number) => {
      return `${index + 1}`;
    },
  },
  {
    title: "业务类型",
    key: "type",
    render: (row: any) => {
      const targetType = getSnTransactionType(row.type);
      return h(
        NTag,
        {
          size: "small",
          type: targetType?.color,
        },
        targetType?.name || "/"
      );
    },
  },
  {
    title: "订单号",
    key: "tradeNum",
  },
  {
    title: "状态",
    key: "currentStatus",
    render: (row: any) => {
      const targetType = getSnStatus(row.currentStatus);
      return h(
        NTag,
        {
          size: "small",
          type: targetType?.color,
        },
        targetType?.name || "/"
      );
    },
  },
  {
    title: "时间",
    key: "createTime",
  },
  {
    title: "查看订单",
    key: "actions",
    align: "right",
    fixed: "right",
    render: (row: any) => {
      return h(
        NButton,
        {
          size: "small",
          type: "primary",
          secondary: true,
          strong: true,
          class: "mr-2",
          onClick: () => {
            handleClickTransactionRecord(row);
          },
        },
        {
          icon: () =>
            h(NIcon, null, {
              default: () => h(Eye),
            }),
        }
      );
    },
  },
];

const props = withDefaults(defineProps<ISnTransactionProps>(), {
  snId: "",
});

const router = useRouter();
const $attrs = useAttrs();

const { tableResult, paginationResult, getDataList, handleChangePage } =
  useTableHook<any>({
    api: getSnTransactionLogs,
    queryForm: {
      variantId: "",
      type: undefined,
      createTimeRange: null,
    },
    beforeFetch: (params) => {
      params.snId = props.snId;
      if (params.createTimeRange) {
        const [start, end] = params.createTimeRange;
        console.log(params);
        if (start) {
          params.createTimeStart = dayjs(start).format("YYYY-MM-DD 00:00:00");
        }

        if (end) {
          params.createTimeEnd = dayjs(end).format("YYYY-MM-DD 23:59:59");
        }
      }
    },
  });

const updateSnResultFlag = ref<boolean>(false);
const snDetailLoading = ref<boolean>(false);
const snCheckResult = ref<any[]>([]);
const originSnCheckResult = ref<any[]>([]);

watch([() => props.snId, () => $attrs.show], ([newVal1, newVal2]) => {
  if (newVal1 && newVal2) {
    init();
  }
});

const handleClickTransactionRecord = (payload: any) => {
  if (payload.id && payload.type) {
    if (payload.type === "tradein") {
      const routeUrl = router.resolve({
        name: RouterNames.TRADEIN_ORDER_DETAIL_PAGE.NAME,
        params: { id: payload.tradeId },
      });
      window.open(routeUrl.href, "_blank");
    }
  }
};

const getSnTransactionType = (value: string): Record<string, any> => {
  let result = {};
  if (value) {
    result = snTransactionTypes[value];
  }
  return result;
};

const getSnStatus = (value: string): Record<string, any> => {
  let result = {};
  if (value) {
    result = snStatus[value];
  }
  return result;
};

const handleUpdateSnCheckResult = debounce(async function () {
  let checkedList: string[] = [];
  let uncheckedList: string[] = [];

  updateSnResultFlag.value = true;

  snCheckResult.value.forEach((item) => {
    if (item.result === "1") {
      checkedList.push(item.id);
    } else {
      uncheckedList.push(item.id);
    }
  });

  const params = {
    checkedList,
    uncheckedList,
  };

  try {
    await updateSnCheckResult(params);
    await handleGetSnCheckResult(props.snId);
  } finally {
    updateSnResultFlag.value = false;
  }
}, 200);

const handleChangeCheckResult = (checkResult: any) => {
  checkResult.result = checkResult.result === "1" ? "0" : "1";
};

const handleResetSnCheckResult = () => {
  snCheckResult.value = cloneDeep(originSnCheckResult.value);
};

const handleGetSnCheckResult = async (snId: string) => {
  if (snId) {
    const result = await getSnCheckResult(snId);
    snCheckResult.value = cloneDeep(get(result, "result") || []);
    originSnCheckResult.value = cloneDeep(get(result, "result") || []);
  }
};

const handleSearch = debounce(function () {
  paginationResult.page = 1;
  getDataList();
}, 200);

const init = async () => {
  snDetailLoading.value = true;
  try {
    await handleGetSnCheckResult(props.snId);
    await getDataList();
  } finally {
    snDetailLoading.value = false;
  }
};
</script>
